#pragma once

#include <vector>
#include <semaphore.h>
#include <pthread.h>
#include <iostream>

static const int default_capacity = 10;

template<class T>
class RingQueue
{
private:
    void P(sem_t& sem)
    {
        sem_wait(&sem);
    }

    void V(sem_t& sem)
    {
        sem_post(&sem);
    }

    void Lock(pthread_mutex_t& mutex)
    {
        pthread_mutex_lock(&mutex);
    }

    void Unlock(pthread_mutex_t& mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    RingQueue(int capacity = default_capacity)
    : _capacity(capacity)
    , _comsumer_step(0)
    , _productor_step(0)
    , _queue(capacity)
    {
        sem_init(&_data_sem, 0, 0);
        sem_init(&_space_sem, 0, _capacity);

        pthread_mutex_init(&_comsumer_mutex, nullptr);
        pthread_mutex_init(&_productor_mutex, nullptr);
    }

    void Push(const T& task)
    {
        P(_space_sem);

        Lock(_productor_mutex);

        _queue[_productor_step++] = task;
        _productor_step %= _queue.size();

        Unlock(_productor_mutex);

        V(_data_sem);
    }

    void Pop(T* task)
    {
        P(_data_sem);

        Lock(_comsumer_mutex);

        *task = _queue[_comsumer_step++];
        _comsumer_step %= _queue.size();

        Unlock(_comsumer_mutex);

        V(_space_sem);
    }

    ~RingQueue()
    {
        sem_destroy(&_data_sem);
        sem_destroy(&_space_sem);

        pthread_mutex_destroy(&_comsumer_mutex);
        pthread_mutex_destroy(&_productor_mutex);
    }

private:
    std::vector<T> _queue;
    int _capacity;

    int _comsumer_step;
    int _productor_step;

    sem_t _data_sem;
    sem_t _space_sem;

    pthread_mutex_t _comsumer_mutex;
    pthread_mutex_t _productor_mutex;
};